/**
 * 日志工具
 */

import { config } from '@/config'

class Logger {
  constructor() {
    this.level = config.development.logLevel
    this.levels = {
      debug: 0,
      info: 1,
      warn: 2,
      error: 3
    }
  }

  shouldLog(level) {
    return this.levels[level] >= this.levels[this.level]
  }

  formatMessage(level, message, ...args) {
    const timestamp = new Date().toISOString()
    const prefix = `[${timestamp}] [${level.toUpperCase()}]`
    return [prefix, message, ...args]
  }

  debug(message, ...args) {
    if (this.shouldLog('debug')) {
      console.debug(...this.formatMessage('debug', message, ...args))
    }
  }

  info(message, ...args) {
    if (this.shouldLog('info')) {
      console.info(...this.formatMessage('info', message, ...args))
    }
  }

  warn(message, ...args) {
    if (this.shouldLog('warn')) {
      console.warn(...this.formatMessage('warn', message, ...args))
    }
  }

  error(message, ...args) {
    if (this.shouldLog('error')) {
      console.error(...this.formatMessage('error', message, ...args))
    }
  }

  // 记录API调用
  apiCall(method, url, data = null) {
    this.debug(`API调用: ${method.toUpperCase()} ${url}`, data)
  }

  // 记录API响应
  apiResponse(method, url, response) {
    this.debug(`API响应: ${method.toUpperCase()} ${url}`, response)
  }

  // 记录API错误
  apiError(method, url, error) {
    this.error(`API错误: ${method.toUpperCase()} ${url}`, error)
  }

  // 记录用户行为
  userAction(action, data = null) {
    this.info(`用户操作: ${action}`, data)
  }

  // 记录性能指标
  performance(name, duration) {
    this.info(`性能指标: ${name} - ${duration}ms`)
  }
}

// 创建全局日志实例
export const logger = new Logger()

// 导出日志类
export default Logger
